ReactJS Ultra For Beginners

🔄 The useEffect Hook


What is useEffect?

  • A React Hook for handling side effects in functional components
  • Replaces componentDidMount, componentDidUpdate, and componentWillUnmount
  • Runs after every render by default
  • Note: Some of the concepts in this sheet are more advanced then where we are now in the course, use this as an eternal cheatsheet for all useEffect related questions.

📝 Basic Syntax

import React, { useState, useEffect } from "react"; function UserProfile() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Side effect code here fetchUserData(); }, []); // Empty dependency array = run only once return ( <div>{loading ? <p>Loading...</p> : <p>Welcome, {user?.name}!</p>}</div> ); }

🔑 Dependency Array

No dependency array (runs after every render):

useEffect(() => { console.log("This runs after every render"); });

Empty dependency array (runs only once):

useEffect(() => { console.log("This runs only once (like componentDidMount)"); }, []);

With dependencies (runs when dependencies change):

useEffect(() => { console.log("This runs when userId changes"); }, [userId]);

🎯 Common Use Cases

1. Data Fetching:

useEffect(() => { const fetchData = async () => { try { const response = await fetch("/api/users"); const data = await response.json(); setUsers(data); } catch (error) { console.error("Error fetching data:", error); } }; fetchData(); }, []); // Empty array = fetch once on mount

2. Event Listeners:

useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener("resize", handleResize); // Cleanup function return () => { window.removeEventListener("resize", handleResize); }; }, []); // Empty array = add listener once

3. Timer/Interval:

useEffect(() => { const interval = setInterval(() => { setCount((prevCount) => prevCount + 1); }, 1000); // Cleanup function return () => clearInterval(interval); }, []); // Empty array = start timer once

⚠️ Important Rules

  • Always include dependencies that are used inside useEffect
  • Use cleanup functions for subscriptions, timers, and event listeners
  • Don't call useEffect inside loops, conditions, or nested functions
  • The cleanup function runs before the effect runs again

🔧 Cleanup Function

useEffect(() => { // Setup const subscription = someAPI.subscribe(); // Cleanup (runs before next effect or on unmount) return () => { subscription.unsubscribe(); }; }, []);

🎯 Best Practices

  1. Keep effects focused - one effect per concern
  2. Use the function form for state updates in effects
  3. Extract complex logic into custom hooks
  4. Always clean up subscriptions and timers